package com.video.moderation.handler;

import com.alibaba.fastjson2.JSONObject;
import com.video.moderation.constant.SecurityConstants;
import com.video.moderation.entity.dto.Result;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component
public class JwtLogoutSuccessHandler implements LogoutSuccessHandler {
    
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        if (authentication != null) new SecurityContextLogoutHandler().logout(request, response, authentication);
        
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader(SecurityConstants.AUTHORIZATION, "");
        SecurityContextHolder.clearContext();

        Result res = Result.success("退出登录成功");
        ServletOutputStream outputStream = response.getOutputStream();

        outputStream.write(JSONObject.toJSONString(res).getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
